package cn.schoolwow.util.module.query.instance.service;

import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.util.domain.query.reflection.QueryReflection;
import cn.schoolwow.util.module.query.instance.domain.InstanceQueryOption;

import java.lang.reflect.Field;

public class SetInstanceFieldValueFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        String fieldName = (String) flowContext.checkData("fieldName");
        Object fieldValue = flowContext.getData("fieldValue");
        InstanceQueryOption instanceQueryOption = flowContext.checkInstanceData(InstanceQueryOption.class);

        if(null==fieldValue){
            return;
        }

        Field field = QueryReflection.newQuery(instanceQueryOption.instance.getClass())
                .ignoreNotExistField(instanceQueryOption.ignoreNotExistField)
                .execute()
                .getField(fieldName);
        if(null!=field){
            //判断类型是否相同
            if(!fieldValue.getClass().getName().equals(field.getType().getName())){
                return;
            }
            field.set(instanceQueryOption.instance, fieldValue);
        }
    }

    public String name() {
        return "通过反射设置实例指定字段的值";
    }
}
